/*
	@author kristina
*/
	// Create a Map that will be placed in the "map" div.

	var IDLE_STATE = 0;
	var SOURCE_SEL_STATE = 1;
	var DEST_SEL_STATE = 2;
	var DISP_ROUTE_STATE = 3;

	var map = null;
	

	var sourcePoint = null;
	var destPoint = null;
	
	var previous_sourcePoint = null;
	var previous_destPoint = null;

	var state = IDLE_STATE;

	var sourceId = -1;
	var destId = -1;
	var colorsArray = ['black','blue','green','red','yellow','pink','olive','cyan','lime','violet'];
	var networks = ["Mers pe jos","Metrou","Tramvai"];
	var toRemove = new Array();

	
	// elements from the document
	var source_id = "source_trig";
	var dest_id = "dest_trig"
	var source_class_idle = "source-idle";
	var dest_class_idle = "dest-idle";
	var source_class_active = "source-sel";
	var dest_class_active = "dest-sel";
	var source_textbox_id = "sourceTextBox";
	var dest_textbox_id = "destTextBox";
	var left_panel_id = "directions";
	var linkurl_textbox_id = "linkTextBox";
	var utils_panel_id = "le";
	var visible_class = "visible";
	var hidden_class = "not_visible";
//<!-- The main function of the script -->


	function getBasePath()
	{
		return "http://" + document.location.hostname + "/ptroute/"; 
	}
	
	function main()
	{
		map = new YMap(document.getElementById('map')); 
		currentId = 1;
		startMap();
	}
	
<!-- Displays the map -->
	function startMap(){
		// Add the ability to change between Sat, Hybrid, and Regular Maps
		map.addTypeControl(); 	
		// Add the zoom control. Long specifies a Slider versus a "+" and "-" zoom control
		map.addZoomLong();    		
		// Add the Pan control to have North, South, East and West directional control
		map.addPanControl();  
		// Specifying the Map starting location and zoom level
		map.drawZoomAndCenter("Bucharest", 2,new YSize(700,700));
		// Verify is there are any parameters in the url
		verifyUrl();
	
		YEvent.Capture(map, EventsList.MouseClick, reportPosition);
		
		function reportPosition(_e, _c){
						
			// These are the current coordonates
			var currentGeoPoint = new YGeoPoint( _c.Lat, _c.Lon );
			
				// zoom ?? 
	/*			var points = new Array(2);
				points[0] = sourcePoint;
				points[1] = destPoint;
				var zoomLevel = map.getZoomLevel(points);
				alert(zoomLevel);
				map.setZoomLevel(zoomLevel);
				map.addZoomScale();*/
				
			// The user wants to change the source point
			if (state == SOURCE_SEL_STATE)
			{
				// There is a source point already selected
				if (sourceId != -1)
				{	// removes the old source point
					map.removeMarker(sourceId);
				}
				sourceId = currentId;
				sourcePoint = currentGeoPoint;
				// display in the textBox the geographical coordonates
				document.getElementById(source_textbox_id).value = _c.Lat.toFixed(6) + " , " + _c.Lon.toFixed(6);	
				document.getElementById(source_id).className = source_class_idle;
				state = IDLE_STATE;
					
			}
			else if (state == DEST_SEL_STATE)
			{
				// There is a source point already selected
				if (destId != -1)
				{	// removes the old source point
					map.removeMarker(destId);
				}
				destId = currentId;
				destPoint = currentGeoPoint;
				// display in the textBox the geographical coordonates
				document.getElementById(dest_textbox_id).value = _c.Lat.toFixed(6) + " , " + _c.Lon.toFixed(6);
				document.getElementById(dest_id).className = dest_class_idle;
				state = IDLE_STATE;
			}
			else 
			{				
				return;			
			}
				
			map.addMarker(currentGeoPoint,currentId+"");
			currentId++;
		}
}
<!-- The source point  will be selected -->
	function pickSource()
	{
		state = SOURCE_SEL_STATE;
		document.getElementById(source_id).className = source_class_active;
		document.getElementById(dest_id).className = dest_class_idle;
				
	}

<!-- the destination point will be selected -->
	function pickDest()
	{
		state = DEST_SEL_STATE;
		document.getElementById(source_id).className = source_class_idle;
		document.getElementById(dest_id).className = dest_class_active;
		
	}		

<!-- Sends the source and the destination points to the server -->
	function sendCoordonates()
	{
		var route = new Array();
		if (sourcePoint == null || destPoint == null)
		{
			alert("Alegeti sursa si destinatia de pe harta!");
			return;
		}
		try
		{
			// sends the the source and teh destination to the server
			JSONRequest.post(getBasePath() + "req/route.php",
					{ source_lat:sourcePoint.Lat,
					  source_lon: sourcePoint.Lon,
					  dest_lat:destPoint.Lat,
					  dest_lon:destPoint.Lon
					},					 
					function(sn, response, exception){
						if (response)
						{
								for (i in response)
								{
									// retrieve the route
									route.push(new Node(response[i].name,response[i].net_id,response[i].line,response[i].lat,response[i].long));
								}

						displayRoute(route);
						displayDirections(route);
						state = IDLE_STATE;
						previous_sourcePoint = sourcePoint;
						previous_destPoint = destPoint;
						sourcePoint = null;
						destPoint = null;
						sourceId = -1;
						destId = -1;

						
						document.getElementById(source_id).className = source_class_idle;
						document.getElementById(dest_id).className = dest_class_idle;
						
						}
						else   
							alert("JSONRequest exception!");
					});
		}
		catch(e) {
			alert(e);
		}
		
	}

<!-- One node from the route -->
	function Node(Name,net_id,line,lat,lon)
	{
		this.Name = Name;
		this.net_id = net_id;
		this.line = line;
		this.lat = lat;
		this.lon = lon;
	}	
	
<!-- Displays the route -->
	function displayRoute(route)
	{
		
		var hashTable = new Array();
		var i = 0;
		var nDistinctLines = 0;
		
		if (route.length > 2)
		{
			// display different colored polylines  for different lines
			while (i < route.length -1)
			{
					var color;
					polylinePoints = [];
					if  (hashTable.hasOwnProperty(route[i].line))
						color = hashTable[route[i].line];
					else
					{
						color = colorsArray[nDistinctLines];
						hashTable[route[i].line] = color;		
					}

					// add source
					polylinePoints.push(new YGeoPoint( route[i].lat, route[i].lon));
					var j = i;
					while (i < route.length -1 && route[i].line == route[i+1].line)
					{	// add the stations from the same line
						position = new YGeoPoint( route[i+1].lat, route[i+1].lon);
						polylinePoints.push(position);
						i++;
					}
					if (j != i)
					{
						displayPolyLine(polylinePoints,color);
						polylinePoints = [];
						polylinePoints.push(new YGeoPoint( route[i].lat, route[i].lon));
						polylinePoints.push(new YGeoPoint( route[i+1].lat, route[i+1].lon)); 
						displayPolyLine(polylinePoints,colorsArray[0]);// by walk
						i++;
						
					}
					else
					{
						i++;
						polylinePoints.push(new YGeoPoint( route[i].lat, route[i].lon));
						displayPolyLine(polylinePoints,colorsArray[0]);// by walk
					}
							
					nDistinctLines++;

				}
		}
		else
		{
			polylinePoints = [];
			polylinePoints.push(new YGeoPoint( route[0].lat, route[0].lon));
			polylinePoints.push(new YGeoPoint( route[1].lat, route[1].lon));
			displayPolyLine(polylinePoints,colorsArray[0]);// by walk

		}
		
		
		// place custom markers for the stations 
		for (i = 1; i<route.length -1 ; i++)
		{
				
			position = new YGeoPoint( route[i].lat, route[i].lon);
			placeMarker(route[i].Name,position,route[i].line,networks[route[i].net_id]);
		}
		
	}
	
	<!-- place a new marker to represent the station -->
	function placeMarker(Name,geoPoint,line,network)
	{
		var newMarker= new YMarker(geoPoint, createCustomMarkerImage());  
	             newMarker.addAutoExpand("<p><b>"+Name+"</b><br>"+line+"</p>");  
		var markerMarkup = "<p>Statia de "+ network.toLowerCase()+"<br><b>"+Name+"</b><br>"+line+"</p>";  
	               
		YEvent.Capture(newMarker, EventsList.MouseClick,   
	                function(){  
	                     newMarker.openSmartWindow(markerMarkup);  
	                 }); 
		map.addOverlay(newMarker);  

	}
	<!-- create custom image for the marker -->
	function createCustomMarkerImage(){  

	        var myImage = new YImage();  
	        myImage.src = 'res/statie_mov.png';  
	        myImage.size = new YSize(20,20);  
	        myImage.offsetSmartWindow = new YCoordPoint(0,0);  
	            return myImage;   
	         
	}
	<!-- displays the polyline in order to represent the route -->
	function displayPolyLine(polylinePoints,color)
	{
		var poly =  new YPolyline(polylinePoints, color,7,0.6);
		map.addOverlay(poly);
		toRemove.push(poly);
	}

	<!-- displays directions -->
	function displayDirections(route)
	{
		var divObj = document.getElementById(left_panel_id);
		
		if (route.length > 2)
		{	// This is not  a direct route
		
        	divObj.innerHTML += "<div class=\"route\"><div class=\"type\"> Mers pe jos </div> pana la statia <a class=\"name\">"+ route[1].Name + " (" + route[1].line + ")"+"</a> </div>";
			var i = 1;
			while (i < route.length -2)
			{
				var nStations = 0;	// counter for the number of the stations
				var j = i;
				while (i < route.length-2 && route[i].line == route[i+1].line && route[i].net_id == route[i+1].net_id)
				{
					nStations ++;
					i++;
				}
				if ( i != j)
				{
				
					divObj.innerHTML += "<div class=\"route\"><div class=\"type\">"+ networks[route[j].net_id] + " " + route[j].line +"</div> de la statia <a class=\"name\">"+ route[j].Name + "</a><br/>pana la statia <a class=\"name\">" + route[i].Name +"</a><div class=\"info\">" + nStations + " statii </div></div>";
				}
				
				if (i < route.length -2)
						divObj.innerHTML += "<div class=\"route\"><div class=\"type\"> Mers pe jos </div> de la statia <a class=\"name\">"+ route[i].Name +" (" + route[i].line + ")</a><br/>pana la statia <a class=\"name\">" + route[i+1].Name +" (" + route[i+1].line + ")</a></div>";
				i++;
				
			}
			divObj.innerHTML += "<div class=\"route\"><div class=\"type\"> Mers pe jos </div> de la statia <a class=\"name\">"+ route[route.length - 2].Name +" (" + route[route.length - 2].line + ")</a><br/>pana la <a class=\"name\">Destinatie</a></div>";
		}
		else
		{
			divObj.innerHTML += "<div class=\"route\"><div class=\"type\"> Mers pe jos </div> pana la <a class=\"name\">Destinatie</a> </div>";
		}		
	}

	<!-- Removes the old route from the map -->
	function clearMap()
	{
		sourcePoint = null;
		destPoint = null;
		state = IDLE_STATE;
		map.removeMarkersAll();
		for (i in toRemove)
			map.removeOverlay(toRemove[i]);
		toRemove = [];
		document.getElementById(source_textbox_id).value = "";
		document.getElementById(dest_textbox_id).value = "";
		document.getElementById(left_panel_id).innerHTML ="";
		
	}
	
	function createLinkUrl() {
	
		var url = location.href;
		var i = url.indexOf("?");
		if (i != -1)
			url = url.substring(0,i);
		if (previous_sourcePoint != null && previous_destPoint != null)
		{
			url +="?";
			url += "source_lat=" + previous_sourcePoint.Lat + "&" +
					"source_lon=" + previous_sourcePoint.Lon + "&" +
					"dest_lat=" + previous_destPoint.Lat + "&" +
					"dest_lon=" + previous_destPoint.Lon;
		}
		document.getElementById(linkurl_textbox_id).value = url;

	}
	function gup( name )
	{
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else{
			return results[1];le
			}
	}

	function verifyUrl()
	{
		var source_lat = gup("source_lat");
		var source_lon = gup("source_lon");
		var dest_lat = gup("dest_lat");
		var dest_lon = gup ("dest_lon");
		
		if (source_lat != "" && source_lon != ""  && dest_lat != "" && dest_lon != "")
		{
			var sourceGeoPoint = new YGeoPoint(source_lat, source_lon);
			var destGeoPoint = new YGeoPoint(dest_lat, dest_lon);
			sourceId = currentId;
			sourcePoint = sourceGeoPoint;
			// display in the textBox the geographical coordonates
			document.getElementById(source_textbox_id).value = (Number(source_lat)).toFixed(6) + " , " + (Number(source_lon)).toFixed(6);	
			document.getElementById(source_id).className = source_class_idle;
	
			map.addMarker(sourceGeoPoint,currentId+"");
			++currentId;
			
			destId = currentId;
			destPoint = destGeoPoint;
			// display in the textBox the geographical coordonates
			document.getElementById(dest_textbox_id).value = (Number(dest_lat)).toFixed(6) + " , " + (Number(dest_lon)).toFixed(6);	
			document.getElementById(dest_id).className = dest_class_idle;
			
			map.addMarker(destGeoPoint,currentId+"");
			++currentId;
			
			state = IDLE_STATE;
			
			sendCoordonates();
		}	
	}
	
	function utilsPanelHide()
	{
		document.getElementById(utils_panel_id).className = hidden_class;
	}
	function utilsPanelOpen()
	{
		createLinkUrl();
		document.getElementById(utils_panel_id).className = visible_class;
	}

